import React, { useState, useEffect } from 'react';
import { Layout, Button, Select, Input, Tabs, message, Table, List, Modal, Form } from 'antd';
import { PlusOutlined, SaveOutlined, EllipsisOutlined, CaretRightOutlined } from '@ant-design/icons';
import axios from '../utils/axios';
import useProjectStore from '../store/projectStore';
import { Dropdown, Menu } from 'antd';
import { API } from '../api';

const { Option } = Select;
const { TabPane } = Tabs;
const { TextArea } = Input;
const { Sider, Content } = Layout;

interface RequestParam {
  key: string;
  value: string;
  description: string;
}

interface RequestGroup {
  id: number;
  name: string;
  projectId: number;
  createdAt: string;
}

interface RequestInterface {
  id?: number;
  name: string;
  method: string;
  url: string;
  params: RequestParam[];
  headers: RequestParam[];
  body: string;
  groupId: number;
}

const ApiDebug: React.FC = () => {
  const [groups, setGroups] = useState<RequestGroup[]>([]);
  const [selectedGroup, setSelectedGroup] = useState<string>('');
  const [method, setMethod] = useState<string>('GET');
  const [url, setUrl] = useState<string>('');
  const [params, setParams] = useState<RequestParam[]>([]);
  const [headers, setHeaders] = useState<RequestParam[]>([]);
  const [body, setBody] = useState<string>('');
  const [response, setResponse] = useState<any>(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [groupName, setGroupName] = useState('');
  const { currentProject } = useProjectStore();
  const [form] = Form.useForm();
  const [interfaceName, setInterfaceName] = useState<string>('');
  const [saveModalVisible, setSaveModalVisible] = useState(false);
  const [testConnectionResult, setTestConnectionResult] = useState<string>('');
  const [expandedGroups, setExpandedGroups] = useState<Record<string, boolean>>({});
  const [groupInterfaces, setGroupInterfaces] = useState<Record<string, RequestInterface[]>>({});

  useEffect(() => {
    if (currentProject) {
      fetchGroups();
    }
  }, [currentProject]);

  const fetchGroups = async () => {
    try {
      const response = await axios.get(API.requestGroup.list(currentProject?.id));
      const sortedGroups = response.data.sort((a: RequestGroup, b: RequestGroup) => 
        new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
      );
      setGroups(sortedGroups);
      if (sortedGroups.length > 0 && !selectedGroup) {
        setSelectedGroup(sortedGroups[0].id.toString());
      }
    } catch (error) {
      message.error('获取接口分组失败');
    }
  };

  const handleCreateGroup = async () => {
    if (!currentProject) {
      message.warning('请先选择项目');
      return;
    }
    setIsModalVisible(true);
  };

  const handleModalOk = async () => {
    try {
      if (!groupName.trim()) {
        message.error('分组名称不能为空');
        return;
      }

      const response = await axios.post(API.requestGroup.create, {
        name: groupName,
        projectId: currentProject?.id
      });
      message.success('创建分组成功');
      setIsModalVisible(false);
      setGroupName('');
      await fetchGroups();
      // 自动选中新创建的分组
      setSelectedGroup(response.data.id.toString());
    } catch (error) {
      message.error('创建分组失败');
    }
  };

  const handleSend = async () => {
    try {
      if (!url.trim()) {
        message.warning('请输入请求URL');
        return;
      }

      const requestData = {
        url: url,
        method: method,
        headers: headers.reduce((acc, curr) => {
          if (curr.key.trim()) {
            acc[curr.key] = curr.value;
          }
          return acc;
        }, {}),
        params: params.reduce((acc, curr) => {
          if (curr.key.trim()) {
            acc[curr.key] = curr.value;
          }
          return acc;
        }, {}),
        body: body ? JSON.parse(body) : null
      };

      const response = await axios.post(API.debug.test, requestData);
      
      setResponse({
        status: response.data.code,
        statusText: response.data.msg,
        data: response.data.data,
        headers: response.data.data.headers,
      });
    } catch (error: any) {
      message.error('请求失败：' + error.message);
    }
  };

  const handleDeleteGroup = async (groupId: string) => {
    try {
      await axios.delete(API.requestGroup.delete(parseInt(groupId)));
      message.success('删除分组成功');
      await fetchGroups();
      if (selectedGroup === groupId) {
        setSelectedGroup(groups[0]?.id.toString() || '');
      }
    } catch (error) {
      message.error('删除分组失败');
    }
  };

  const handleEditGroup = async (groupId: string, newName: string) => {
    try {
      await axios.put(API.requestGroup.update(parseInt(groupId)), {
        name: newName
      });
      message.success('更新分组成功');
      await fetchGroups();
    } catch (error) {
      message.error('更新分组失败');
    }
  };

  const paramColumns = [
    {
      title: '参数名',
      dataIndex: 'key',
      key: 'key',
      width: '30%',
      render: (_: any, record: RequestParam, index: number) => (
        <Input
          value={record.key}
          onChange={e => {
            const newParams = [...params];
            newParams[index].key = e.target.value;
            setParams(newParams);
          }}
          placeholder="参数名"
        />
      ),
    },
    {
      title: '参数值',
      dataIndex: 'value',
      key: 'value',
      width: '30%',
      render: (_: any, record: RequestParam, index: number) => (
        <Input
          value={record.value}
          onChange={e => {
            const newParams = [...params];
            newParams[index].value = e.target.value;
            setParams(newParams);
          }}
          placeholder="参数值"
        />
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      width: '30%',
      render: (_: any, record: RequestParam, index: number) => (
        <Input
          value={record.description}
          onChange={e => {
            const newParams = [...params];
            newParams[index].description = e.target.value;
            setParams(newParams);
          }}
          placeholder="描述"
        />
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: '10%',
      render: (_: any, _record: RequestParam, index: number) => (
        <Button
          type="link"
          danger
          onClick={() => {
            const newParams = [...params];
            newParams.splice(index, 1);
            setParams(newParams);
          }}
        >
          删除
        </Button>
      ),
    },
  ];

  const getGroupMenu = (group: RequestGroup) => (
    <Menu
      items={[
        {
          key: 'rename',
          label: '重命名',
          onClick: () => {
            const newName = prompt('请输入新的分组名称', group.name);
            if (newName && newName !== group.name) {
              handleEditGroup(group.id.toString(), newName);
            }
          }
        },
        {
          key: 'addInterface',
          label: '新增接口',
          onClick: () => {
            setSelectedGroup(group.id.toString());
            // 重置表单
            setMethod('GET');
            setUrl('');
            setParams([{ key: '', value: '', description: '' }]);
            setHeaders([{ key: '', value: '', description: '' }]);
            setBody('');
          }
        },
        {
          key: 'delete',
          label: '删除',
          danger: true,
          onClick: () => {
            if (window.confirm('确定要删除该分组吗？')) {
              handleDeleteGroup(group.id.toString());
            }
          }
        }
      ]}
    />
  );

  const fetchGroupInterfaces = async (groupId: string) => {
    try {
      const response = await axios.get(API.requestInterface.list(parseInt(groupId)));
      setGroupInterfaces(prev => ({
        ...prev,
        [groupId]: response.data
      }));
    } catch (error) {
      message.error('获取接口列表失败');
    }
  };

  const handleToggleGroup = (groupId: string) => {
    setExpandedGroups(prev => {
      const newState = { ...prev, [groupId]: !prev[groupId] };
      if (newState[groupId]) {
        fetchGroupInterfaces(groupId);
      }
      return newState;
    });
  };

  const renderGroupList = () => (
    <div style={{ padding: '16px' }}>
      <div style={{ marginBottom: '16px' }}>
        <Button 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={handleCreateGroup}
          style={{ width: '100%' }}
        >
          新建分组
        </Button>
      </div>
      <List
        dataSource={groups}
        renderItem={group => (
          <>
            <List.Item
              style={{
                cursor: 'pointer',
                background: selectedGroup === group.id.toString() ? '#e6f7ff' : 'transparent',
                padding: '8px 16px',
                borderRadius: '4px',
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center'
              }}
            >
              <div style={{ display: 'flex', alignItems: 'center', flex: 1 }}>
                <CaretRightOutlined 
                  rotate={expandedGroups[group.id] ? 90 : 0}
                  onClick={(e) => {
                    e.stopPropagation();
                    handleToggleGroup(group.id.toString());
                  }}
                  style={{ marginRight: 8 }}
                />
                <span onClick={() => setSelectedGroup(group.id.toString())}>
                  {group.name}
                </span>
              </div>
              <Dropdown 
                overlay={getGroupMenu(group)} 
                trigger={['click']}
                placement="bottomRight"
              >
                <EllipsisOutlined
                  style={{ fontSize: '20px', padding: '4px' }}
                  onClick={e => e.stopPropagation()}
                />
              </Dropdown>
            </List.Item>
            {expandedGroups[group.id] && groupInterfaces[group.id]?.map(apiInterface => (
              <List.Item
                key={apiInterface.id}
                style={{
                  marginLeft: 24,
                  padding: '4px 16px',
                  cursor: 'pointer'
                }}
                onClick={() => loadInterface(apiInterface)}
              >
                {apiInterface.name}
              </List.Item>
            ))}
          </>
        )}
      />
    </div>
  );

  const loadInterface = (apiInterface: RequestInterface) => {
    setMethod(apiInterface.method);
    setUrl(apiInterface.url);
    setHeaders(JSON.parse(apiInterface.headers));
    setParams(JSON.parse(apiInterface.params));
    setBody(apiInterface.body);
  };

  const handleSaveInterface = async () => {
    if (!selectedGroup) {
      message.warning('请先选择分组');
      return;
    }

    if (!interfaceName.trim()) {
      message.warning('请输入接口名称');
      return;
    }

    try {
      const interfaceData = {
        name: interfaceName,
        method,
        url,
        params,
        headers,
        body,
        groupId: parseInt(selectedGroup)
      };

      await axios.post(API.requestInterface.create, interfaceData);
      message.success('保存成功');
      setSaveModalVisible(false);
      setInterfaceName('');
    } catch (error) {
      message.error('保存失败');
    }
  };

  const handleTestConnection = async () => {
    try {
      const response = await axios.get(url);
      setTestConnectionResult(`连接成功 (${response.status})`);
    } catch (error: any) {
      if (error.response) {
        setTestConnectionResult(`连接失败 (${error.response.status}): ${error.response.statusText}`);
      } else {
        setTestConnectionResult('连接失败: 无法连接到服务器');
      }
    }
  };

  const renderMainContent = () => (
    <div style={{ padding: '24px' }}>
      <div style={{ display: 'flex', gap: '16px', marginBottom: '16px' }}>
        <Select
          style={{ width: 100 }}
          value={method}
          onChange={setMethod}
        >
          <Option value="GET">GET</Option>
          <Option value="POST">POST</Option>
          <Option value="PUT">PUT</Option>
          <Option value="DELETE">DELETE</Option>
        </Select>
        <Input
          style={{ flex: 1 }}
          value={url}
          onChange={e => setUrl(e.target.value)}
          placeholder="请输入请求URL"
        />
        <Button type="primary" onClick={handleSend}>
          发送
        </Button>
        <Button 
          type="primary" 
          icon={<SaveOutlined />} 
          onClick={() => setSaveModalVisible(true)}
        >
          保存
        </Button>
      </div>

      <Tabs defaultActiveKey="1">
        <TabPane tab="Params" key="1">
          <div style={{ marginBottom: '16px' }}>
            <Button
              type="primary"
              onClick={() => setParams([...params, { key: '', value: '', description: '' }])}
            >
              添加参数
            </Button>
          </div>
          <Table
            columns={paramColumns}
            dataSource={params}
            pagination={false}
            rowKey={(record, index) => index?.toString() || '0'}
          />
        </TabPane>
        <TabPane tab="Headers" key="2">
          <div style={{ marginBottom: '16px' }}>
            <Button
              type="primary"
              onClick={() => setHeaders([...headers, { key: '', value: '', description: '' }])}
            >
              添加请求头
            </Button>
          </div>
          <Table
            columns={paramColumns}
            dataSource={headers}
            pagination={false}
            rowKey={(record, index) => index?.toString() || '0'}
          />
        </TabPane>
        <TabPane tab="Body" key="3">
          <TextArea
            rows={10}
            value={body}
            onChange={e => setBody(e.target.value)}
            placeholder="请输入JSON格式的请求体"
          />
        </TabPane>
        <TabPane tab="Response" key="4">
          {response && (
            <div>
              <div style={{ marginBottom: '16px' }}>
                <div style={{ 
                  color: response.error ? '#ff4d4f' : '#52c41a',
                  marginBottom: '8px'
                }}>
                  状态: {response.status} {response.statusText}
                </div>
                {response.duration && (
                  <div>耗时: {response.duration}ms</div>
                )}
              </div>
              <Tabs defaultActiveKey="body">
                <TabPane tab="Body" key="body">
                  <TextArea
                    rows={20}
                    value={JSON.stringify(response.data, null, 2)}
                    readOnly
                  />
                </TabPane>
                <TabPane tab="Headers" key="headers">
                  <TextArea
                    rows={10}
                    value={JSON.stringify(response.headers, null, 2)}
                    readOnly
                  />
                </TabPane>
              </Tabs>
            </div>
          )}
        </TabPane>
      </Tabs>
    </div>
  );

  return (
    <Layout style={{ background: '#fff', height: '100%' }}>
      <Sider width={250} theme="light" style={{ borderRight: '1px solid #f0f0f0' }}>
        {renderGroupList()}
      </Sider>
      <Content>
        {renderMainContent()}
      </Content>
      <Modal
        title="新建分组"
        visible={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => {
          setIsModalVisible(false);
          setGroupName('');
        }}
      >
        <Form form={form}>
          <Form.Item label="分组名称">
            <Input
              value={groupName}
              onChange={e => setGroupName(e.target.value)}
              placeholder="请输入分组名称"
            />
          </Form.Item>
        </Form>
      </Modal>
    </Layout>
  );
};

export default ApiDebug; 